const {Sequelize, DataTypes, Op} = require('sequelize');
require('dotenv').config(); // 加载 .env 文件到 process.env

const {DB_PASSWORD, DB_USER} = process.env

const sequelize = new Sequelize('chooseBikes', DB_USER, DB_PASSWORD, {
    host: 'localhost',
    dialect: 'mysql',
    dialectOptions: {
        dateStrings: true,
        typeCast: true,
    },
    timezone: '+08:00', //东八区时间
    logging: false
});

const User = require('../model/user.model')(sequelize, DataTypes);
const Role = require('../model/role.model')(sequelize, DataTypes);
const UserRole = require('../model/userRole.model')(sequelize, DataTypes);
const Menu = require('../model/menu.model')(sequelize, DataTypes);
const RolePermission = require('../model/rolePermission.model')(sequelize, DataTypes);
const Brand = require('../model/brand.model')(sequelize, DataTypes);
const Bike = require('../model/bike.model')(sequelize, DataTypes);
const Comment = require('../model/comment.model')(sequelize, DataTypes);
const Feedback = require('../model/feedback.model')(sequelize, DataTypes);

const AppletUser = require('../model/appletUser.model')(sequelize, DataTypes);
const AppletBikeCollect = require('../model/appletCollect.model')(sequelize, DataTypes);
const AppletBikeScore = require('../model/appletBikeScore.model')(sequelize, DataTypes);

const WxAppletUser = require('../model/wxAppletUser.model')(sequelize, DataTypes);


User.belongsToMany(Role, {
    through: UserRole,
    foreignKey: 'userId',
    otherKey: 'roleId',
    onUpdate: 'CASCADE',
    onDelete: 'CASCADE'
})

Role.belongsToMany(User, {
    through: UserRole,
    foreignKey: 'roleId',
    otherKey: 'userId',
    onUpdate: 'CASCADE',
    onDelete: 'CASCADE'
})

Menu.belongsToMany(Role, {
    through: RolePermission,
    foreignKey: 'permissionId',
    otherKey: 'roleId',
    onUpdate: 'CASCADE',
    onDelete: 'CASCADE'
})

Role.belongsToMany(Menu, {
    through: RolePermission,
    foreignKey: 'roleId',
    otherKey: 'permissionId',
    onUpdate: 'CASCADE',
    onDelete: 'CASCADE'
})

Bike.hasMany(Comment)
Comment.belongsTo(Bike)

Bike.hasMany(AppletBikeScore)
AppletBikeScore.belongsTo(Bike)

// Comment.sync({alter: true})
// WxAppletUser.sync({force: true})
// AppletBikeScore.sync({force: true})
// Bike.sync({alter: true})
// User.restore({
//     where: {
//         id: 4
//     }
// })
// AppletUser.sync({alter: true})


sequelize.authenticate().then(() => {
    console.log('连接数据库成功');
}).catch((err) => {
    console.log('连接数据库失败', err)
})

module.exports = {
    sequelize,
    User,
    UserRole,
    Role,
    Menu,
    RolePermission,
    Brand,
    Bike,
    AppletUser,
    WxAppletUser,
    Comment,
    AppletBikeCollect,
    Feedback,
    AppletBikeScore,
    Op
}
